<template>
  <div
    class="upload-area"
    :class="{ 'is-dragover': isDragover }"
    @dragover.prevent="handleDragOver"
    @dragleave.prevent="handleDragLeave"
    @drop.prevent="handleDrop"
    @paste="handlePaste"
  >
    <el-upload
      class="upload-input"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
    >
      <div class="upload-content">
        <el-icon :size="48" color="#4a6fa5"><Upload /></el-icon>
        <p class="upload-text">拖拽图片到此处，或点击上传</p>
        <p class="upload-hint">支持粘贴图片（Ctrl+V）</p>
      </div>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['upload'])
const isDragover = ref(false)

// 处理拖拽相关事件
const handleDragOver = () => {
  isDragover.value = true
}

const handleDragLeave = () => {
  isDragover.value = false
}

const handleDrop = (e) => {
  isDragover.value = false
  const files = Array.from(e.dataTransfer.files)
  handleFiles(files)
}

// 处理粘贴事件
const handlePaste = async (e) => {
  const items = Array.from(e.clipboardData.items)
  
  for (const item of items) {
    if (item.type.startsWith('image/')) {
      const file = item.getAsFile()
      if (file) {
        await handleFiles([file])
        break
      }
    }
  }
}

// 处理文件选择
const handleFileChange = (file) => {
  handleFiles([file.raw])
}

// 统一处理文件
const handleFiles = async (files) => {
  const imageFiles = files.filter(file => file.type.startsWith('image/'))
  
  if (imageFiles.length === 0) {
    ElMessage.warning('请上传图片文件')
    return
  }
  
  for (const file of imageFiles) {
    try {
      emit('upload', {
        file,
        type: 'file'
      })
    } catch (error) {
      console.error('处理文件失败:', error)
      ElMessage.error('处理文件失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 12px;
  padding: 40px 20px;
  text-align: center;
  margin: 20px;
  background: rgba(74, 111, 165, 0.05);
  transition: all 0.3s;
  cursor: pointer;
  
  &.is-dragover {
    border-color: #4a6fa5;
    background: rgba(74, 111, 165, 0.1);
  }
  
  &:hover {
    border-color: #4a6fa5;
    background: rgba(74, 111, 165, 0.1);
  }
  
  .upload-input {
    width: 100%;
  }
  
  .upload-content {
    .upload-text {
      margin: 15px 0 8px;
      font-size: 16px;
      color: #606266;
    }
    
    .upload-hint {
      font-size: 14px;
      color: #909399;
    }
  }
}
</style> 